package com.qiongqi.datadir.utils.file;

// 文件：PdfRenderingWithWatermarkUtil.java
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;

public final class PdfRenderingUtils {

    /**
     * 将 PDF 的指定页渲染为带水印的图片（JPEG/PNG）
     *
     * @param pdfPath    PDF 文件路径
     * @param pageIndex  页码（从 0 开始）
     * @param username   当前用户
     * @param ip         用户 IP
     * @param maxWidth   输出图片最大宽度（用于响应式）
     * @return 图片字节数组（JPEG 格式）
     * @throws IOException
     */
    public static byte[] renderPageWithWatermark(
            String pdfPath,
            int pageIndex,
            String username,
            String ip,
            int maxWidth) throws IOException {

        try (PDDocument document = PDDocument.load(new java.io.File(pdfPath))) {
            if (pageIndex < 0 || pageIndex >= document.getNumberOfPages()) {
                throw new IllegalArgumentException("Invalid page index: " + pageIndex);
            }

            PDFRenderer renderer = new PDFRenderer(document);
            BufferedImage image = renderer.renderImageWithDPI(pageIndex, 150); // 150 DPI 清晰度

            // 创建水印图层
            Graphics2D g = image.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            // 将颜色改为深蓝色
            g.setColor(new Color(0, 0, 139, 120)); // 深蓝色，透明度 120
            g.setFont(new Font("SansSerif", Font.BOLD, 28));

            // 获取当前时间
            String timestamp = new Date().toString();
            // 获取服务器 IP（可选）
            String serverIp = InetAddress.getLocalHost().getHostAddress();

            // 水印文本
            String watermarkText = String.format("User: %s | IP: %s | Time: %s | Server: %s",
                    username, ip, timestamp, serverIp);

            // 绘制多个水印（斜向重复）
            int gap = 150;
            g.rotate(-Math.PI / 6);
            for (int x = -image.getHeight(); x < image.getWidth(); x += gap) {
                for (int y = 0; y < image.getHeight() + gap; y += gap) {
                    g.drawString(watermarkText, x, y);
                }
            }
            g.dispose();

            // 缩放（如果需要）
            if (image.getWidth() > maxWidth) {
                double ratio = (double) maxWidth / image.getWidth();
                int newHeight = (int) (image.getHeight() * ratio);
                Image scaled = image.getScaledInstance(maxWidth, newHeight, Image.SCALE_SMOOTH);
                BufferedImage resized = new BufferedImage(maxWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                Graphics2D g2 = resized.createGraphics();
                g2.drawImage(scaled, 0, 0, null);
                g2.dispose();
                image = resized;
            }

            // 输出为 JPEG
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
            return baos.toByteArray();
        }
    }

    // 可选：添加“禁止打印”元数据（仅象征性）
    public static void addSecurityMetadata(String inputPath, String outputPath) throws IOException {
        try (PDDocument doc = PDDocument.load(new java.io.File(inputPath))) {
            doc.getDocumentInformation().setCreator("Secure Document System");
            doc.getDocumentInformation().setTitle("Confidential - Do Not Distribute");

            // 禁止打印、复制（仅对遵守规范的阅读器有效）
            AccessPermission ap = new AccessPermission();
            ap.setCanPrint(false);
            ap.setCanExtractContent(false);
            ap.setCanModify(false);

            StandardProtectionPolicy policy = new StandardProtectionPolicy("", "", ap);
            policy.setEncryptionKeyLength(128);
            doc.protect(policy);
            doc.save(outputPath);
        }
    }
}